package com.jdk.demo.nio.bytebuffer;

import java.nio.ByteBuffer;

public class CompactDemo {
	
	// 压缩，将缓冲区的当前位置和限制之间的字节(如果有)，复制到缓冲区的开始处，即将索引p=position处的字节复制到索引0处，将索引p+1处的字节复制到索引1处，
	// 依次类推，直到将索引limit-1处的字节复制到索引n=limit-1-p处，然后将position设置为n+1，将限制设置为容量
	public static void main(String[] args) {
		ByteBuffer bytebuffer1 = ByteBuffer.wrap(new byte[]{1, 2, 3, 4, 5, 6});
		System.out.println("A bytebuffer1 capacity=" + bytebuffer1.capacity() + ", position=" + bytebuffer1.position() + " limit=" + bytebuffer1.limit());
		System.out.println("1 getValue=" + bytebuffer1.get());
		System.out.println("B bytebuffer1 capacity=" + bytebuffer1.capacity() + ", position=" + bytebuffer1.position() + " limit=" + bytebuffer1.limit());
		System.out.println("2 getValue=" + bytebuffer1.get());
		System.out.println("C bytebuffer1 capacity=" + bytebuffer1.capacity() + ", position=" + bytebuffer1.position() + " limit=" + bytebuffer1.limit());
		bytebuffer1.compact();
		System.out.println("D bytebuffer1 capacity=" + bytebuffer1.capacity() + ", position=" + bytebuffer1.position() + " limit=" + bytebuffer1.limit());
		byte[] getByteArray = bytebuffer1.array();
		for (int i = 0; i < getByteArray.length; i++) {
			System.out.print(getByteArray[i] + " ");
		}
		System.out.println();
	}

}
